package cn.com.git.example.module.service.impl;

import cn.com.git.example.common.ResultMsgFactory;
import cn.com.git.example.common.ResultPage;
import cn.com.git.example.common.exception.ApiException;
import cn.com.git.example.common.util.object.MapperFacadeUtils;
import cn.com.git.example.module.dao.mapper.DemoMapper;
import cn.com.git.example.module.dao.model.Demo;
import cn.com.git.example.module.service.DemoService;
import cn.com.git.example.module.service.dto.DemoDTO;
import cn.com.git.example.module.service.dto.DemoSaveForm;
import cn.com.git.example.module.service.query.DemoListQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zhangzhenfu
 * @Description
 * @date 2021/3/6 0006 10:43
 */
@Slf4j
@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private DemoMapper demoMapper;

    @Override
    public ResultPage<DemoDTO> listDemo(DemoListQuery query) {
        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<Demo> list = demoMapper.selectListByQuery(query);
        PageInfo<Demo> pageInfo = PageInfo.of(list);
        return ResultMsgFactory.transfer(pageInfo, DemoDTO.class);
    }

    @Override
    public DemoDTO findDemo(Integer id) {
        Demo demo = demoMapper.selectByPrimaryKey(id);
        return MapperFacadeUtils.map(demo, DemoDTO.class);
    }

    @Transactional
    @Override
    public Integer addDemo(DemoSaveForm saveForm) {
        DemoDTO demoDTO = DemoSaveForm.TO.apply(saveForm);
        Demo demo = MapperFacadeUtils.map(demoDTO, Demo.class);
        demoMapper.insertSelective(demo);
        demoDTO.setId(demo.getId());
        return demo.getId();
    }

    @Transactional
    @Override
    public void editDemo(DemoSaveForm saveForm) {
        Demo demo = MapperFacadeUtils.map(saveForm, Demo.class);
        int i = demoMapper.updateByPrimaryKeySelective(demo);
        if (i == 0) {
            throw new ApiException("数据失效");
        }
    }

    @Transactional
    @Override
    public void deleteSysUser(Integer id) {
        int i = demoMapper.deleteByPrimaryKey(id);
        if (i == 0) {
            throw new ApiException("数据失效");
        }
    }
}
